<?php
/**
 * 开源中国OAuth支持类
 * 
 * @author ShuangYa
 * @package EasyAccount
 * @category Library
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2017 ShuangYa
 * @license https://www.sylibs.com/go/easyaccount/license
 */
namespace ea\library\OAuthClient;
use \Swoole\Coroutine as co;
use \Swoole\Coroutine\Http\Client;

class OSChina implements OAuthInterface {
	const ID = 3;

	const API_DOMAIN = 'www.oschina.net';
	const API_PORT = 443;
	const API_SSL = TRUE;
	const API_URL = 'https://www.oschina.net/';

	protected static $config = NULL;

	public static function set($config) {
		self::$config = $config;
	}

	public static function getAuthorizeURL($redirect_uri) {
		return self::API_URL . 'action/oauth2/authorize?' . http_build_query([
			'client_id' => self::$config['client_id'],
			'response_type' => 'code',
			'redirect_uri' => $redirect_uri
		]);
	}

	public static function getAccessToken($code, $redirect_uri) {
		$data = [
			'client_id' => self::$config['client_id'],
			'client_secret' => self::$config['client_secret'],
			'grant_type' => 'authorization_code',
			'code' => $code,
			'redirect_uri' => $redirect_uri,
			'dataType' => 'json'
		];
		$ip = co::gethostbyname(self::API_DOMAIN);
		$client = new Client($ip, self::API_PORT, self::API_SSL);
		$client->setHeaders([
			'Host' => self::API_DOMAIN
		]);
		$client->get('/action/openapi/token?' . http_build_query($data));
		$result = json_decode($client->body, 1);
		return [
			'id' => $result['uid'],
			'access_token' => $result['access_token']
		];
	}

	public static function getMyInfo($token) {
		$data = 'access_token=' . urlencode($token) . '&dataType=json';
		$ip = co::gethostbyname(self::API_DOMAIN);
		$client = new Client($ip, self::API_PORT, self::API_SSL);
		$client->setHeaders([
			'Host' => self::API_DOMAIN
		]);
		$client->get('/action/openapi/user?' . $data);
		$result = json_decode($client->body, 1);
		return [
			'id' => $result['id'],
			'name' => $result['name'],
			'avatar' => $result['avatar']
		];
	}
}